package com.tianqi.ui;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianqi.ui.bean.WeatherForecast;
import com.tianqi.ui.bean.WeatherInfo;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class WeatherApp {
    public static void main(String[] args) throws IOException {
    //    模拟查询
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入查询城市：");
        String city = sc.next();

    //    1.构建一个客户端
        CloseableHttpClient client = HttpClients.createDefault();
    //    2.构建有一个请求对象
        HttpGet doGet = new HttpGet("https://api.iyk0.com/6rtq/?city="+city);
    //    3.发送请求，服务器回应我们一个json的字符串
        CloseableHttpResponse response = client.execute(doGet);
    //    response.getEntity():获取响应种的一个实体
        String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
        System.out.println(jsonStr);

    //    4.解析 jsonStr -->WeatherForecast对象   借助jackson
        ObjectMapper mapper = new ObjectMapper();
        WeatherForecast forecast = mapper.readValue(jsonStr,WeatherForecast.class);

    //    4.1判断城市是否存在
        if("1002".equals(forecast.getDesc())){
            System.out.println("你输入的城市无效！");
            return;
        }

    //    5.解析对象的信息
    //    5.1 当前城市
        String cityName =forecast.getData().getCity();
        System.out.println("所在城市："+cityName);
    //    5.2 查询程序今日往后的5天的天气预报
        List<WeatherInfo> weathers = forecast.getData().getForecast();
    //    5.3 遍历每天天气信息
        for(WeatherInfo w:weathers){
            System.out.println("日期："+w.getDate());
            System.out.println("天气："+w.getType());
            System.out.println("最高温度："+w.getHigh());
            System.out.println("最低温度："+w.getLow());
            System.out.println("风向："+w.getFengxiang());
            System.out.println("风力："+w.getFengli());
            System.out.println("--------------------------");
        }
    }
}
